package cn.bocweb.spinning.view.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

import java.util.List;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ConfigTable;
import cn.bocweb.spinning.model.Bean.DownloadFirstBean;
import cn.bocweb.spinning.model.Bean.FirstMatchBean;
import cn.bocweb.spinning.model.Bean.SecondMatch;
import cn.bocweb.spinning.model.Bean.SecondTestBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.model.Imp.BaseModelImp;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.AES256Utils;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.MyDbHelper;
import cn.bocweb.spinning.view.dialog.LoadingDialog;
import cn.bocweb.spinning.view.fragment.TestRuleNoticeFragment;
import de.greenrobot.event.EventBus;


public class TestRuleActivity extends BaseActivity {

    String url1, title, libtype, lastTime;
    UserPresenter mUserPresenter;
    LoadingDialog mLoadingDialog;
    Intent intent;
    boolean isFirst;
    //    DBHelper dbHelper = new DBHelper(this);
    MyDbHelper dbHelper = new MyDbHelper();
    DbUtils db;
    UserPresenter mPresenter;
    UserBean.DataEntity dataEntity;
    TestRuleNoticeFragment testRuleNoticeFragment;

    @Bind(R.id.test_rule)
    WebView mTestRule;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @BindColor(R.color.white)
    int white;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_rule);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        mUserPresenter = new UserPresenterImp();
        mLoadingDialog = new LoadingDialog(this);
        mPresenter = new UserPresenterImp();
        dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(TestRuleActivity.this);
        db = dbHelper.getDbInstance(this);
        initIntent();
        initToolbar();
        initWebView();
        testRuleNoticeFragment = new TestRuleNoticeFragment();
        mLoadingDialog.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mTestRule.loadUrl(url1);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Constant.REWARD_TO_LOGIN: {
                if (resultCode == Constant.REWARD_TO_LOGIN) {
                    if (mLoadingDialog == null) {
                        mLoadingDialog = new LoadingDialog(this);
                        mLoadingDialog.show();
                    } else {
                        mLoadingDialog.show();
                    }
                    UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                    dataEntity.readInfoFromLocal(TestRuleActivity.this);

                }
                break;
            }
            case Constant.TEST_RULE_BACK_LOGIN: {
                break;
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    private void initWebView() {

        WebSettings settings = mTestRule.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mTestRule.setWebChromeClient(new WebChromeClient());
//        mTestRule.setDownloadListener(new MyWebViewDownLoadListener());
        mTestRule.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype, long contentLength) {
                System.out.println("=========>开始下载 url =" + url);
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        mTestRule.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                dialog.dismiss();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.contains("http://match/")) {
                    lastTime = queryData(libtype);
                    if (TextUtils.isEmpty(dataEntity.getUserid())) {
                        Intent intent = new Intent(TestRuleActivity.this, LoginAcivity.class);
                        intent.putExtra(Constant.ACTIVITY_TO_LOGIN, 102);
                        intent.putExtra(Constant.ACTIVITY_TO_LOGIN_LIB, libtype);
                        intent.putExtra(Constant.TO_TEST_RULE, url1);
                        intent.putExtra(Constant.TO_TEST_RULE_TITLE, title);
                        startActivity(intent);
                    } else {

                        mUserPresenter.secondTest(dataEntity.getUserid(), libtype, lastTime);
                    }
                    return true;
                } else if (url.contains("http://rank/")) {
                    Intent intent = new Intent(TestRuleActivity.this, RankActivity.class);
                    intent.putExtra(Constant.TO_RANK_LIBID, libtype);
                    intent.putExtra(Constant.TO_TEST_RANK_IF_SECOND, true);
                    intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
                    startActivity(intent);
                    return true;
                } else if (url.contains("http://common/")) {

                    if (TextUtils.isEmpty(dataEntity.getUserid())) {
                        Intent intent = new Intent(TestRuleActivity.this, LoginAcivity.class);
                        intent.putExtra(Constant.ACTIVITY_TO_LOGIN, 103);
                        intent.putExtra(Constant.ACTIVITY_TO_LOGIN_LIB, libtype);
                        startActivity(intent);
                    } else {
                        String id = dataEntity.getUserid();
                        Intent intent = new Intent(TestRuleActivity.this, ReadyTestActivity.class);
                        intent.putExtra(Constant.TO_READY_TEST_NORMAL, libtype);
                        intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
                        startActivity(intent);
                    }
                    return true;
                } else {
                    view.loadUrl(url);
                    return true;
                }
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mLoadingDialog.dismiss();
            }
        });
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mTestRule.canGoBack()) {
            mTestRule.goBack();
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_BACK) && !mTestRule.canGoBack()) {
            finish();
            return true;
        }
        return false;
    }

//    public void onEventMainThread(FirstRewardBean bean) {
//        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
//            mLoadingDialog.dismiss();
//        }
//        intent = new Intent(this, FirstRewardActivity.class);
//        intent.putExtra(Constant.TO_FIRST_REWARD, bean.getUrl());
//        intent.putExtra(Constant.TO_TEST_RANK_IF_FIRST, true);
//        startActivity(intent);
//    }

    private void deleByLib(String libtype) {
        String timeline = String.valueOf(System.currentTimeMillis() / 1000L);
        try {
            db.delete(ConfigTable.class, WhereBuilder.b("libtype", "=", libtype));
            db.delete(SecondMatch.class, WhereBuilder.b("libtype", "=", libtype));

        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    public void onEventMainThread(FirstMatchBean bean) {
        if (bean.getReturn_code() == 0) {
            Intent intent = new Intent(TestRuleActivity.this, ReadyTestActivity.class);
            intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, bean.getId());
            Log.e("==id==", "" + bean.getId());
            intent.putExtra(Constant.TO_TEST_RANK_IF_FIRST, true);
            intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
            intent.putExtra(Constant.TO_REDAY_TEST_QTITLE, bean.getFirst());
            startActivity(intent);
            isFirst = true;
//            finish();
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(SecondTestBean bean) {

        if (bean.getReturn_code() == 0) {
            for (int i = 0; i < bean.getExamdata().size(); i++) {
                String libtype1 = bean.getExamdata().get(i).getLibtype();
                String snum = bean.getExamdata().get(i).getSnum();
                String jnum = bean.getExamdata().get(i).getJnum();
                String dnum = bean.getExamdata().get(i).getDnum();
                int code = bean.getExamdata().get(i).getCode();
                String spoint = bean.getExamdata().get(i).getSpoint();
                String jpoint = bean.getExamdata().get(i).getJpoint();
                String dpoint = bean.getExamdata().get(i).getDpoint();
                String require = bean.getExamdata().get(i).getRequire();
                String examtitle = bean.getExamdata().get(i).getExamtitle();
                String timelimit = bean.getExamdata().get(i).getTimelimit();
                String timeline = bean.getExamdata().get(i).getTimeline();
                String type = bean.getExamdata().get(i).getType();
                String start = bean.getExamdata().get(i).getStart();
                String end = bean.getExamdata().get(i).getEnd();
                String ishuadong = bean.getExamdata().get(i).getIshuadong();
                String isdatika = bean.getExamdata().get(i).getIsdatika();
                String ischange = bean.getExamdata().get(i).getIschange();
                String myorder = bean.getExamdata().get(i).getMyorder();
                String isresit = bean.getExamdata().get(i).getIsresit();
                String iserror = bean.getExamdata().get(i).getIserror();
                if (code == 101) {
                    Log.e("====", "101");
                } else if (code == 103) {
                    deleByLib(libtype1);
                    Toast.makeText(this, "系统繁忙，请稍候", Toast.LENGTH_SHORT).show();
                    Log.e("====", "103");
                } else if (code == 104) {
                    Intent intent = new Intent(TestRuleActivity.this, ReadyTestActivity.class);
                    intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, bean.getExamdata().get(0).getLibtype());
                    intent.putExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, true);
                    intent.putExtra(Constant.TO_SECOND_RULE_END_TIME, bean.getExamdata().get(0).getLasttime());
                    intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
                    startActivity(intent);
                    Log.e("====", "104");
                } else if (code == 105) {
                    Log.e("====", "105");
                    deleByLib(libtype1);
                    ConfigTable configTable = new ConfigTable();
                    configTable.setLibtype(libtype1);
                    configTable.setSnum(snum);
                    configTable.setDnum(dnum);
                    configTable.setJnum(jnum);
                    configTable.setIsdatika(isdatika);
                    configTable.setIshuadong(ishuadong);
                    configTable.setIschange(ischange);
                    configTable.setSpoint(spoint);
                    configTable.setJpoint(jpoint);
                    configTable.setDpoint(dpoint);
                    configTable.setRequire(require);
                    configTable.setTitle(examtitle);
                    configTable.setTimelimit(timelimit);
                    configTable.setStart(start);
                    configTable.setEnd(end);
                    configTable.setType(type);
                    configTable.setTimeline(timeline);
                    configTable.setMyorder(myorder);
                    configTable.setIserror(iserror);
                    configTable.setIsresit(isresit);
                    try {
                        db.save(configTable);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    for (int j = 0; j < bean.getExamdata().get(i).getData().size(); j++) {

                        String id = bean.getExamdata().get(i).getData().get(j).getId();
                        String title = AES256Utils.getInstance().addSecureToStr(bean.getExamdata().get(i).getData().get(j).getTitle());
                        String ttype = bean.getExamdata().get(i).getData().get(j).getTtype();
                        String explain = AES256Utils.getInstance().addSecureToStr(bean.getExamdata().get(i).getData().get(j).getExplain());
                        List<String> right = bean.getExamdata().get(i).getData().get(j).getRight();
                        Gson gson = new Gson();
                        String rightJson = gson.toJson(right);
                        List<String> option = (bean.getExamdata().get(i).getData().get(j).getOption());
                        String optionJson = gson.toJson(option);
                        String libtype = bean.getExamdata().get(i).getData().get(j).getLibtype();
                        //实例化一个ContentValues， ContentValues是以键值对的形式，键是数据库的列名，值是要插入的值
                        SecondMatch secondMatch = new SecondMatch();
                        if (optionJson.isEmpty() || optionJson.equals("") || optionJson == null) {
                            secondMatch.setOption("");
                        } else {
                            secondMatch.setOption(optionJson);
                        }
                        secondMatch.setQuestionid(id);
                        secondMatch.setTitle(title);
                        secondMatch.setTtype(ttype);
                        secondMatch.setLibtype(libtype);
                        secondMatch.setExplain(explain);
                        secondMatch.setRight(rightJson);

                        //调用insert插入数据库
                        try {
                            db.save(secondMatch);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    Intent intent = new Intent(TestRuleActivity.this, ReadyTestActivity.class);
                    intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, bean.getExamdata().get(0).getLibtype());
                    intent.putExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, true);
                    intent.putExtra(Constant.TO_SECOND_RULE_END_TIME, bean.getExamdata().get(0).getLasttime());
                    intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
                    startActivity(intent);
                } else {
                    Log.e("====", "error" + code);
                }
            }
            DeviceUtil.Log("题目获取成功");


        } else if (bean.getReturn_code() == -1) {
            DeviceUtil.Log("题目获取失败");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    private String queryData(String ltype) {
        ConfigTable configTable = new ConfigTable();
        String lastTime = "";
        //调用query()获取Cursor
        try {
            configTable = db.findFirst(Selector.from(ConfigTable.class).where("libtype", "=", ltype));
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (configTable != null) {
            if (!configTable.getTimeline().isEmpty() || configTable.getTimeline() != null) {
                lastTime = configTable.getTimeline();
            }
            return lastTime;
        } else {
            return lastTime;
        }

    }
    private void initIntent() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        url1 = bundle.getString(Constant.TO_TEST_RULE);
        title = bundle.getString(Constant.TO_TEST_RULE_TITLE);
        if (bundle.getString(Constant.TO_TEST_RULE_LIBTYPE) != null) {
            libtype = bundle.getString(Constant.TO_TEST_RULE_LIBTYPE);
        }

        if (!TextUtils.isEmpty(url1)) {
            mTestRule.loadUrl(url1);
        }
    }

    private void initToolbar() {
        mToolbar.setTitle(title);
        mToolbar.setTitleTextColor(white);
        mToolbar.setNavigationIcon(R.mipmap.btn_exit);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}
